<?php
!defined('IN_ROOT') && exit( 'Access Denied' );
class SwapController extends AdminModuleController
{
	public function actionAdmin() {		
		$page = intval(getgpc('page'));
		$page = max(1, $page);
		
		$sqladd = '';
		$title = getgpc('title', 'R');
		if($title) {
			$sqladd = "title like '%$title%' AND";
		}
		$userName = getgpc('userName', 'R');
		if ($userName) {
			$sqladd = "userName like '%$userName%' AND";
		}
		$sqladd = substr($sqladd, 0, -3);
		
		$swapList = $this->GiftsSwapModel->findAll($sqladd, $page, GODHOUSE_PPP3, ' swapId DESC');
		foreach($swapList as &$v) {
			$v['statusName'] = Lookup::item('status', $v['status']);
			$v['createdTime'] = date('Y-m-d H:i:s', $v['createdTime']);
		}
		$num = $this->GiftsSwapModel->count($sqladd);
		$multipage = page($num, GODHOUSE_PPP3, $page, 'swap-admin.htm');
		
		$this->view->assign('swapList', $swapList);
		$this->view->assign('title', $title);
		$this->view->assign('userName', $userName);
		$this->view->assign('multipage', $multipage);
		$this->display('swap_admin');
	}
	
	public function actionDelete() {
		$swapId = getgpc(2);
		if($swapId) {
			$swap = $this->GiftsSwapModel->findByPk($swapId);
			if(!$swap) {
				$this->message('操作失败，数据不存在。', GODHOUSE_DOMAIN_WWW.'admin/swap-admin.htm');
			}
			$this->GiftsSwapModel->DeleteByPk($swapId);
			$this->message('操作成功。', GODHOUSE_DOMAIN_WWW.'admin/swap-admin.htm');
		} elseif ($swapIds = getgpc('swapId', 'P')) {
			foreach($swapIds as $swapId) {
				$this->GiftsSwapModel->DeleteByPk($swapId);
			}
			$this->message('操作成功。', GODHOUSE_DOMAIN_WWW.'admin/swap-admin.htm');
		}
	}
	
	public function actionStatus() {
		$swapId = getgpc(2);
		$status = getgpc(3);
		
		$swap = $this->GiftsSwapModel->findByPk($swapId);
		if($swap) {
			$user = $this->UserModel->findByPk($swap['userId']);
			if($swap['credit'] > $user['credit']) {
				$this->message('操作失败，'.$user['userName'].'用户积分('.$user['credit'].')不够。', GODHOUSE_DOMAIN_WWW.'admin/swap-admin.htm');
			}
			
			$att = array(
				'status'=>$status,
			);
			if($status == GODHOUSE_STATUS_COMPLETED) {
				// 库存减一
				$this->GiftsModel->updateByPk($swap['giftsId'], array('inventory'=>'-1'));	
				// 积分相减
				$this->UserModel->updateByPk($swap['userId'], array('credit'=>"-{$swap['credit']}"));
			}
			$this->GiftsSwapModel->updateByPk($swapId, $att);
			$this->message('操作成功。', GODHOUSE_DOMAIN_WWW.'admin/swap-admin.htm');
		} else {
			$this->message('操作的数据不存在。', GODHOUSE_DOMAIN_WWW.'admin/swap-admin.htm');
		}
	}
}